<template>
  <div class="register-view">
    <Header />
    
    <div class="register-container">
      <div class="register-card">
        <div class="register-header">
          <h2>创建账号</h2>
          <p>欢迎加入二手交易平台</p>
        </div>
        
        <el-form 
          :model="form" 
          :rules="rules" 
          ref="registerForm" 
          class="register-form"
        >
          <el-form-item prop="username">
            <el-input 
              v-model="form.username" 
              placeholder="请输入账户名"
              size="large"
              :prefix-icon="User"
            />
          </el-form-item>
          
          <el-form-item prop="phone">
            <el-input 
              v-model="form.phone" 
              placeholder="请输入手机号"
              size="large"
              :prefix-icon="Iphone"
            >
              <template #append>
                <el-button @click="sendSmsCode" :disabled="smsCountdown > 0">
                  {{ smsCountdown > 0 ? `${smsCountdown}s后重发` : '发送验证码' }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item prop="smsCode">
            <el-input 
              v-model="form.smsCode" 
              placeholder="请输入验证码"
              size="large"
              :prefix-icon="Message"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input 
              v-model="form.password" 
              type="password" 
              placeholder="请输入密码"
              size="large"
              :prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          
          <el-form-item prop="confirmPassword">
            <el-input 
              v-model="form.confirmPassword" 
              type="password" 
              placeholder="请确认密码"
              size="large"
              :prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          
          <el-form-item>
            <el-checkbox v-model="agreement">
              我已阅读并同意
              <el-link type="primary" :underline="false">《用户协议》</el-link>
              和
              <el-link type="primary" :underline="false">《隐私政策》</el-link>
            </el-checkbox>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              size="large" 
              class="register-btn"
              :loading="loading"
              @click="handleRegister"
            >
              注册
            </el-button>
          </el-form-item>
        </el-form>
        
        <div class="register-footer">
          <p>已有账号？
            <el-link type="primary" :underline="false" @click="goToLogin">
              立即登录
            </el-link>
          </p>
        </div>
      </div>
    </div>
    
    <Footer />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Iphone, Message, Lock } from '@element-plus/icons-vue'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import { register } from '@/api/auth.js'

const router = useRouter()
const registerForm = ref()
const loading = ref(false)
const agreement = ref(false)
const smsCountdown = ref(0)

const form = reactive({
  username: '',
  phone: '',
  smsCode: '',
  password: '',
  confirmPassword: ''
})

const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请确认密码'))
  } else if (value !== form.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, message: '请输入账户名', trigger: 'blur' },
    { min: 2, max: 20, message: '账户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ]
}

const sendSmsCode = () => {
  if (!form.phone) {
    ElMessage.error('请输入手机号')
    return
  }
  
  // 模拟发送验证码
  smsCountdown.value = 60
  const timer = setInterval(() => {
    smsCountdown.value--
    if (smsCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
  
  ElMessage.success('验证码已发送')
}

const handleRegister = async () => {
  try {
    if (!agreement.value) {
      ElMessage.error('请阅读并同意用户协议和隐私政策')
      return
    }
    
    await registerForm.value.validate()
    
    loading.value = true
    
    // 调用后端注册API
    const response = await register({
      username: form.username,
      phone: form.phone,
      smsCode: form.smsCode,
      password: form.password,
      confirmPassword: form.confirmPassword
    })
    
    ElMessage.success('注册成功！')
    loading.value = false
    router.push('/login')
  } catch (error) {
    loading.value = false
    
    // 更具体的错误提示
    if (error.data) {
      const errorData = error.data
      
      // 处理字段级别的错误
      if (typeof errorData === 'object') {
        let hasFieldErrors = false
        for (const field in errorData) {
          if (Array.isArray(errorData[field]) && errorData[field].length > 0) {
            // 将字段名转换为中文描述
            const fieldName = getFieldChineseName(field)
            ElMessage.error(`${fieldName}: ${errorData[field][0]}`)
            hasFieldErrors = true
          }
        }
        if (!hasFieldErrors && errorData.message) {
          ElMessage.error(errorData.message)
        } else if (!hasFieldErrors) {
          ElMessage.error('注册失败，请检查输入信息')
        }
      } else if (errorData.message) {
        ElMessage.error(errorData.message)
      } else {
        ElMessage.error('注册失败，请检查输入信息')
      }
    } else if (error.message === 'Network Error') {
      ElMessage.error('网络错误，请检查您的网络连接')
    } else {
      ElMessage.error('注册失败，请检查输入信息')
    }
    console.error('Register error:', error)
  }
}

const goToLogin = () => {
  router.push('/login')
}

// 将字段名转换为中文描述
const getFieldChineseName = (field) => {
  const fieldMap = {
    'username': '用户名',
    'phone': '手机号', 
    'smsCode': '验证码',
    'password': '密码',
    'confirmPassword': '确认密码',
    'non_field_errors': '通用错误'
  }
  return fieldMap[field] || field
}
</script>

<style scoped>
.register-view {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.register-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.register-card {
  background: white;
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h2 {
  color: #333;
  margin-bottom: 10px;
  font-size: 28px;
}

.register-header p {
  color: #666;
  margin: 0;
}

.register-form {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

.register-btn {
  width: 100%;
  border-radius: 8px;
  height: 48px;
  font-size: 16px;
}

.register-footer {
  text-align: center;
}

.register-footer p {
  color: #666;
  margin: 0;
}
</style>